import axios from 'axios';
import request from './request';

window.myCache = (function () {
    const stateMaxLength = 4;
    const localMaxLength = 4;
    const prefix = 'api_'

    window._myCache = {};               //  全局状态缓存
    window._myCacheArr = [[], []];      //  记录全局状态缓存、localStorage索引

    //  init local
    window._myCacheArr[1] = myLocalStorage.keys().filter(key => {
        const reg =  new RegExp('^' + prefix);
        return reg.test(key);
    });

    return {
        get: function ({api, data, mode = 'state', expire = 0}) {   //  只对get请求做缓存，post不做缓存
            const key = prefix + api + (data && `-${JSON.stringify(data)}` || '');

            let res;

            if (window._myCache[key]) {
                res = window._myCache[key];
            } else if (myLocalStorage.getItem(key)) {
                res = myLocalStorage.getItem(key);
            }

            if (res) {
                return new Promise((resolve, reject) => {
                    resolve(res);
                });
            } else {
                return this.set({api, data, mode, key, expire});
            }
        },
        set: function ({api, data, mode = 'state', key, expire = 0}) {
            return request({
                url: api,
                method: 'get',
                params: data,
            }).then(res => {
                this.saveData(mode, key, res, expire);
                return Promise.resolve(res);
            }, err => {
                return Promise.reject(err);
            })
        },
        saveData: function (mode, key, data, expire) {
            if (mode === 'state') {
                if (window._myCacheArr[0].length >= stateMaxLength) {
                    const top = window._myCacheArr[0].shift();
                    this.remove(top)
                }

                window._myCache[key] = data;
                window._myCacheArr[0].push(key);
            } else if (mode === 'local') {
                if (window._myCacheArr[1].length >= localMaxLength) {
                    const top = window._myCacheArr[1].shift();
                    this.remove(top)
                }

                myLocalStorage.setItem(key, data, expire);
                window._myCacheArr[1].push(key);
            }
        },
        remove: function (key) {
            delete window._myCache[key];
            myLocalStorage.removeItem(key);

        },
        removeAll: function () {
            window._myCache = {}
            window._myCacheArr[1].forEach(key => {
                myLocalStorage.removeItem(key);
            })
            window._myCacheArr = [[], []];
        }
    }
}());